package com.wolfsea.rvitemdecorationdemo.ui.dashboard
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.wolfsea.rvitemdecorationdemo.R
import com.wolfsea.rvitemdecorationdemo.bean.Contact
import com.wolfsea.rvitemdecorationdemo.databinding.FragmentDashboardBinding
import com.wolfsea.rvitemdecorationdemo.itemdecoration.DefineItemDecoration
import com.wolfsea.rvitemdecorationdemo.itemdecoration.SuspendItemDecoration
import com.wolfsea.rvitemdecorationdemo.rvadapter.DashboardRvAdapter

class DashboardFragment : Fragment() {

    private var _binding: FragmentDashboardBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        val dashboardViewModel =
            ViewModelProvider(this).get(DashboardViewModel::class.java)

        _binding = FragmentDashboardBinding.inflate(inflater, container, false)
        val root: View = binding.root
        //val textView: TextView = binding.textDashboard
        //dashboardViewModel.text.observe(viewLifecycleOwner) {
        //    textView.text = it
        //}
        init(dashboardViewModel, binding)
        return root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun init(model: DashboardViewModel, binding: FragmentDashboardBinding) {

        val linearLayoutManager = LinearLayoutManager(requireContext())
        //val itemDecoration = DefineItemDecoration(requireContext(),DefineItemDecoration.VERTICAL).apply {
        //    setDrawable(resources.getDrawable(R.drawable.dashboard_rv_item_decoration))
        //}
        val itemDecoration = SuspendItemDecoration(requireContext()).apply {
            dividerDrawable = resources.getDrawable(R.drawable.dashboard_rv_item_decoration)
            dividerGroupDrawable = resources.getDrawable(R.drawable.dashboard_rv_group_decoration)
            model.dashDataSet.observe(viewLifecycleOwner) {
                contacts = it
            }
        }

        val dashBoardAdapter = DashboardRvAdapter().apply {
            model.dashDataSet.observe(viewLifecycleOwner) {
                items = it
            }
        }

        binding.dashRv.apply {
            layoutManager = linearLayoutManager
            adapter = dashBoardAdapter
            addItemDecoration(itemDecoration)
        }
    }

}